package com.wfy.modules.sys.secutiry;

import com.google.gson.Gson;
import com.wfy.common.entity.Result;
import com.wfy.common.entity.ResultGenerate;
import com.wfy.common.security.shiro.utils.ShiroHolder;
import com.wfy.common.util.Servlets;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: wangxindong
 * Date: 2017/7/6
 * Time: 09:37
 */
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter {

    private String redirectUrl;

    @Override
    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest resq = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        ShiroHolder.getSubject().logout();
        if (Servlets.isAjaxRequest(resq)) {
            Result result = ResultGenerate.getSuccessResult();
            Servlets.writeResponse(resp, new Gson().toJson(result));
            return false;
        } else {
            issueRedirect(request, response, redirectUrl);
            return false;
        }
    }
}
